/*
 * main.c
 *
 *  Created on: Mar 20, 2015
 *      Author: rj
 */
#include "sys/types.h"
#include "sys/socket.h"
#include "stdio.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "errno.h"
#include "stdlib.h"
#include "string.h"

#define MAXBUF	1024

int main(int argc, char **argv) {

	int sockfd, len, pid;
	struct sockaddr_in address;
	int result;
	char buf[MAXBUF+1];
	
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = inet_addr("127.0.0.1");
	address.sin_port = 9734;
	len = sizeof(address);
	result = connect(sockfd, (struct sockaddr *) &address, len);

	if(result == -1) {
		perror("连接失败！");
		exit(errno);
		return 1;
	} else {
		printf("server connected.");
	}
	
	if(-1 == (pid=fork())) {
		perror("fork");
		exit(EXIT_FAILURE);
	} else if (0 == pid) {
		while(1) {
			bzero(buf, MAXBUF+1);
			len = recv(sockfd, buf, MAXBUF, 0);
			if (len >0) 
				printf("<=====：%s,%d字节\n", buf, len);
			else if(len<0) {
				perror("recv");exit(EXIT_FAILURE);
			} else {
				printf("对方退出。\n");
				exit(0);
				break;
			}
		}
	} else {
		while(1) {
			bzero(buf, MAXBUF+1);
			//printf("请输入信息：\n");
			fgets(buf, MAXBUF, stdin);
			if (!strncasecmp(buf, "quit", 4)) {
				printf("you choose to quit.\n"); 
				exit(0);
				break;
			}
			//发送
			len = send(sockfd, buf, strlen(buf)-1, 0);
			if (len < 0) {
				printf("发送失败！\n");
				break;
			}
		}
	}
	close(sockfd);
	return 0;
}


